<template>
  <a-modal :visible="show" width="85vw" :bodyStyle="{ padding: '10px' }" title="质量通知单" @ok="handleCancel"
    @cancel="handleCancel" :pagination="false" :footer="null">
    <a-button type="primary" @click="createQuality" class="hte-btn">新增</a-button>
    <a-button @click="fetchQualityList" class="hte-btn">刷新</a-button>
    <a-radio-group v-model="platForm" @change="changePlatForm">
      <a-radio-button value="1"> 海芯 </a-radio-button>
      <a-radio-button value="2"> 海澜 </a-radio-button>
    </a-radio-group>
    <a-table :columns="[...qualityColumns, ...deleteColums]" :data-source="qualityRecords" rowKey="id" bordered
      @change="qualityHandleTableChange" :customRow="customQualityRow">
      <span slot="billTypeRender" slot-scope="text, record">
        <div v-for="(item, index) in billTypeOptions" :key="index">
          <span v-if="item.value == record.billType">
            {{ item.label }}
          </span>
        </div>
      </span>
      <span slot="qualityNoRender" slot-scope="text, record">
        <span class="font-active" @click="toQualityDetail(record)">
          {{ record.qualityNo }}
        </span>
      </span>
      <template slot="handlerStepRender" slot-scope="text, record">
        {{ record.handlerStep }}
      </template>
      <template slot="currentHandlerRender" slot-scope="text, record">
        {{ currentHandlerRenderFunc(record) }}
      </template>
      <span slot="actionRender" slot-scope="text, record">
        <span
          v-if="record.platForm == '海芯' && ((['1','3'].indexOf(record.status)>-1 && record.applyUserId==currUserId) || (record.status=='0'))"
          class="font-active" @click="toDelQuality(record)"> 删除 </span>
        <span v-else class="font-active"> </span>
      </span>
    </a-table>
    <a-pagination v-if="qualityRecords.length > 0" style="padding: 15px 30px" v-model="pagination.current"
      :page-size-options="pageSizeOptions" :total="pagination.total" show-size-changer :page-size="pagination.pageSize"
      @change="pageChange" @showSizeChange="onShowSizeChange" :show-total="(total) => `共 ${total} 条`">
      <template slot="buildOptionText" slot-scope="props">
        <span v-if="props.value !== '50'">{{ props.value }}条/页</span>
        <span v-if="props.value === '50'">全部</span>
      </template>
    </a-pagination>
  </a-modal>
</template>
<script>
import Vue from 'vue'
import { ACCESS_TOKEN, USER_INFO } from '@/store/mutation-types'
import { getAction, postAction } from '@/api/manage'
import { Modal } from 'ant-design-vue'
export default {
  components: {},
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    poNo: {
      type: String,
      default: null,
    },
    permission: {
      type: Array,
      default: () => {
        return []
      },
    },
  },
  computed: {
    loadList() {
      return this.show
    },
  },
  data() {
    return {
      currUserId: this.$store.getters.userInfo.username,
      deleteColums: [
        {
          title: '操作',
          width: '5%',
          align: 'center',
          scopedSlots: { customRender: 'actionRender' },
        },
      ],
      qualityColumns: [
        {
          title: '当前步骤',
          dataIndex: 'handlerStep',
          scopedSlots: { customRender: 'handlerStepRender' },
          width: '100px',
          align: 'center',
        },
        {
          title: '当前处理人/接收时间/停留时间',
          dataIndex: 'handlerUser',
          scopedSlots: { customRender: 'currentHandlerRender' },
          width: '220px',
          align: 'center',
        },
        {
          title: '单据类型',
          dataIndex: 'billType',
          width: '150px',
          align: 'center',
          scopedSlots: { customRender: 'billTypeRender' },
        },
        {
          title: '质量通知单',
          dataIndex: 'qualityNo',
          width: '150px',
          align: 'center',
          scopedSlots: { customRender: 'qualityNoRender' },
        },
        {
          title: 'OA流水号',
          dataIndex: 'oaLsh',
          width: '180px',
          align: 'center',
        },
        {
          title: '申请人',
          dataIndex: 'applyUser',
          width: '80px',
          align: 'center',
        },
        {
          title: '合同名称',
          dataIndex: 'contractName',
          width: '200px',
          align: 'center',
        },
        {
          title: '采购订单号',
          dataIndex: 'poNo',
          width: '100px',
          align: 'center',
        },
        {
          title: '扣款金额',
          dataIndex: 'fineAmount',
          width: '100px',
          align: 'center',
        },
        {
          title: '来源',
          dataIndex: 'platForm',
          width: '60px',
          align: 'center',
        },
      ],
      billTypeOptions: [
        { value: 1, label: '扣罚类(含非扣罚的质量问题)' },
        { value: 2, label: '非扣罚类' },
      ],
      urls: {
        psQualityList: '/hte/contract/qualityList',
        hteQualityList: '/workReport/quality/page',
        delQuality: '/workReport/quality/delete',
        myPermission: '/workReport/project/myPermission',
      },

      qualityModel: false,
      pagination: {
        current: 1,
        pageSize: 10,
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        total: 0,
      },
      pageSizeOptions: ['10', '20', '30'],
      qualityRecords: [],
      psQualityRecords: [],
      hteQualityRecords: [],
      platForm: "1"
    }
  },
  mounted() { },
  methods: {
    fetchPermission() {
      getAction(this.urls.myPermission, { projectId: this.task.projectId }).then((res) => {
        if (res.success) {
          this.permission = res.result
        }
      })
    },
    checkPermission(powers) {
      let hasPower = false
      for (let p of powers) {
        if (this.permission.indexOf(p) > -1) {
          hasPower = true
          break
        }
      }
      return hasPower
    },
    customQualityRow(record) {
      return {
        on: {
          dblclick: (event) => {
            let urlJump = this.$router.resolve({ path:'/workReport/quality/view/' + record.id + '/' + this.taskId })
          window.open(urlJump.href, '_blank')
            this.$emit('hide')
          },
        },
      }
    },
    toQualityDetail(record) {
      if (record.platForm == '海澜') {
        let urlJump = this.$router.resolve({ path:'/workReport/quality/view/' + record.id + '/' + this.taskId })
          window.open(urlJump.href, '_blank')
      } else {
        let urlJump = this.$router.resolve({ path:'/workReport/editQuality/' + record.id })
          window.open(urlJump.href, '_blank')
      }
      this.$emit('hide')
    },
    changePlatForm() {
      this.$set(this.pagination, 'current', 1)
      this.$set(this.pagination, 'pageNo', 1)
      this.fetchQualityList()
    },
    fetchQualityList() {
      this.qualityRecords = []
      this.psQualityRecords = []
      this.hteQualityRecords = []
      if (this.platForm == "2") {
        this.fetchPsQualityList()
      }
      if (this.platForm == "1") {
        this.fetchHteQualityList()
      }
    },
    fetchPsQualityList() {
      // if (this.pagination.current == 0 || this.pagination.current == 1) {
      let param = {}
      param.poNo = this.poNo
      param.pageNo = this.pagination.current
      // param.pageSize = 10000
      postAction(this.urls.psQualityList, param).then((res) => {
        if (res.success) {
          this.psQualityRecords = res.result.records
          this.psQualityRecords.forEach((r) => {
            r.platForm = '海澜'
            if (r.status != '3' && r.status != '4') {
              r.fineAmount = ''
            }
          })
          this.$set(this.pagination, 'total', res.result.total)
          this.qualityRecords = this.psQualityRecords
        }
      })
      // } else {
      //   this.psQualityRecords = []
      // }
    },
    fetchHteQualityList() {
      let param = {}
      param.poNo = this.poNo
      param.pageNo = this.pagination.current
      param.pageSize = this.pagination.pageSize
      param.taskId = this.taskId
      postAction(this.urls.hteQualityList, param).then((res) => {
        if (res.success) {
          this.hteQualityRecords = res.result.records
          this.hteQualityRecords.forEach((r) => {
            r.platForm = '海芯'
          })
          this.$set(this.pagination, 'total', res.result.total)
          this.qualityRecords = this.hteQualityRecords
        }
      })
    },
    /**
     * 表结构切换页码
     */
    qualityHandleTableChange(pagination, filters, sorter) {
      this.pagination = pagination
      this.pagination.pageNo = this.pagination.current
      this.fetchQualityList()
    },
    currentHandlerRenderFunc(record) {
      let text = ''
      if (record.handlerUser) {
        if (record.handlerTime) {
          // text = record.handlerUser + '/' + record.handlerTime
          // var startDate = new Date(record.handlerTime).getTime()
          // var endDate = new Date().getTime()
          // var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000)
          // text += '/' + parseInt(days) + '天'
          text = record.handlerUser + '/' + record.handlerTime + '/' + record.stayDays + '天'
        }
      }
      return text
    },
    toDelQuality(record) {
      if (record.platForm == '海澜') {
        return this.$messageWorkReport.warning('该质量通知单来源为[海澜],请前往海澜操作删除')
      }
      // if (record.status == '1' || record.status == '2') {
      //   return this.$messageWorkReport.warning('质量通知单状态为审批中或审批通过，请勿删除')
      // }
      // if (!this.checkPermission(['WORK_REPORT_MANAGER'])) {
      //   if (record.crtUserId != this.userinfo.info.username) {
      //     return this.$messageWorkReport.warning('请勿删除非本人创建的质量通知单')
      //   }
      // }
      let that = this
      Modal.confirm({
        title: '提醒',
        content: '是否确认删除质量通知单[' + record.qualityNo + ']',
        onOk() {
          postAction(that.urls.delQuality + '/' + record.id, {}).then((res) => {
            if (res.success) {
              that.$messageWorkReport.success('删除成功')
              that.fetchQualityList()
            } else {
              that.$messageWorkReport.error('删除失败')
            }
          })
        },
        onCancel() { },
      })
    },
    handleCancel() {
      this.$emit('hide')
    },
    pageChange(pageNo, pageSize) {
      this.$set(this.pagination, 'pageSize', pageSize)
      this.$set(this.pagination, 'pageNo', pageNo)
      this.fetchQualityList()
    },
    onShowSizeChange(current, pageSize) {
      this.pagination.current = 1
      this.pagination.pageSize = pageSize
      this.fetchQualityList()
    },
    createQuality(){
      this.$emit("createQuality")
      this.$emit('hide')
    }
  },
  watch: {
    loadList(newV, oldV) {
      if (newV) {
        this.$set(this.pagination, 'current', 1)
        this.fetchQualityList()
      }
    },
  },
}
</script>
<style lang="less" scoped>
@import '~@assets/less/hte-main.less';

.page-main {
  .container {
    .content {
      margin-top: 20px;

      section {
        .section-table {
          .add-btn {
            margin-left: 0;
            margin-bottom: 10px;
          }
        }
      }
    }
  }

  .tips-box {
    margin-top: 32px;

    .add-btn {
      width: 180px;
      height: 40px;
      line-height: 40px;
      background-color: #4095e4;
      border-radius: 2px;
    }
  }
}

.icon-file {
  background-image: url('~@assets/file.png');
}

.cr-content-pop {
  p {
    margin-bottom: 15px;
    color: #666;

    &:last-child {
      margin-bottom: 0;
    }
  }
}
</style>